//
//  DrRobotViewController.m
//  DrRobot
//
//  Created by Zoltan Szeredi on 6/11/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DrRobotViewController.h"
#import "netcom.h"
#import "packet.h"
#import "robot.h"
#import "pms5005.h"
#import <pthread.h>
#import <stdlib.h>
#import <time.h>

@implementation DrRobotViewController

@synthesize addressField;
@synthesize portField;
@synthesize pingButton;
@synthesize debugConsole;
@synthesize amountField;    
@synthesize forwardButton;
@synthesize backwardButton;
@synthesize leftButton;
@synthesize rightButton;
@synthesize percentageSlider;

@synthesize infraredProgress1;
@synthesize infraredProgress2;
@synthesize infraredProgress3;
@synthesize infraredProgress4;
@synthesize infraredProgress5;
@synthesize infraredProgress6;

@synthesize ultrasonicProgress1;
@synthesize ultrasonicProgress2;
@synthesize ultrasonicProgress3;
@synthesize ultrasonicProgress4;
@synthesize ultrasonicProgress5;
@synthesize ultrasonicProgress6;

+(double) ad2dis:(unsigned int) advalue
{
	double dis = 0.0;
    
	if (advalue > 4096 || advalue <= 0) {
		dis = 0.0;
	} else {
		dis = 21.600000000001 / (((double) advalue *3.0) / 4028.0 -
                                 0.17000000000001);
		
		if ( dis > 80.0 ) {
			dis = 0.810000000005;
		} else if ( dis < 10.0 ) {
			dis = 0.089999999999997;
		} else {
			dis /= 100.0;	
		}
	}
    
	return dis;
}

-(void) update_gui
{
    time_t *now;
    float newval[6];
    
    now = time(NULL);
    srand(now);
    
    NSLog(@"Raw Data %u:%u:%u:%u:%u:%u", conn->data->custom_ad[0],
                                        conn->data->custom_ad[1],
                                        conn->data->custom_ad[2],
                                        conn->data->custom_ad[3],
                                        conn->data->custom_ad[4],
                                        conn->data->custom_ad[5]);
    
    for (int i=0; i<6; i++) {
        newval[i] = [DrRobotViewController ad2dis:conn->data->custom_ad[i]];
    }

//    [infraredProgress1 setProgress:newval[0]];
    [infraredProgress1 setProgress: newval[0]];
    [infraredProgress2 setProgress: newval[1]];
    [infraredProgress3 setProgress: newval[2]];
    [infraredProgress4 setProgress: newval[3]];
    [infraredProgress5 setProgress: newval[4]];
    [infraredProgress6 setProgress: newval[5]];

    [ultrasonicProgress1 setProgress: (double)conn->data->us_range[0]/300.0];
    [ultrasonicProgress2 setProgress: (double)conn->data->us_range[1]/300.0];
    [ultrasonicProgress3 setProgress: (double)conn->data->us_range[2]/300.0];
    [ultrasonicProgress4 setProgress: (double)conn->data->us_range[3]/300.0];
    [ultrasonicProgress5 setProgress: (double)conn->data->us_range[4]/300.0];
    [ultrasonicProgress6 setProgress: (double)conn->data->us_range[5]/300.0];
    
    
    NSLog(@"Values changed to %f:%f:%f:%f:%f:%f", newval[0], newval[1], newval[2], newval[3], newval[4], newval[5]);
}

-(IBAction) pingButtonClicked:(id)sender
{
    NSLog(@"Ping Button Clicked");
    NSLog(@"Address: %@;\tPort: %@;", [addressField text], [portField text]);
    
    unsigned char stream[MAX_PACKET_LEN];
    packet_t *packet = NULL;
    
    packet = ping_pms5005();
    packet_serialize(packet, stream);
    packet_delete(packet);
    
    connection_new_robot(&conn, (char *)[[addressField text] UTF8String], (unsigned short) [[portField text] intValue]);
    connection_send_stream(conn, stream, packet_stream_length(stream));
    connection_get_data(conn);
    
    NSThread *dummyThread = [[NSThread alloc] initWithTarget:self selector:@selector(update_gui) object:nil];
    [dummyThread release];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(update_gui) userInfo:nil repeats:YES];
    
    NSMutableString *tempString;
    tempString = [[NSMutableString alloc] initWithString:[debugConsole text]];
    [tempString appendString:@"\nSending Robot Ping Packet!"];
    [debugConsole setText:tempString];
    [tempString release];
}

-(IBAction) forwardButtonClicked : (id)sender
{
    unsigned char stream[MAX_PACKET_LEN];
    packet_t *packet = NULL;
    float amount = [[amountField text] floatValue] * [percentageSlider value];
    
    packet = robot_move(conn->data, amount);
    packet_serialize(packet, stream);
    packet_delete(packet);
    
    connection_send_stream(conn, stream, packet_stream_length(stream));
    
    NSMutableString *tempString;
    tempString = [[NSMutableString alloc] initWithString:[debugConsole text]];
    [tempString appendString:@"\nSending Robot Move Forward Packet!"];
    [debugConsole setText:tempString];
    [tempString release];
}

-(IBAction) backwardButtonClicked : (id)sender
{
    unsigned char stream[MAX_PACKET_LEN];
    packet_t *packet = NULL;
    float amount = -[[amountField text] floatValue] * [percentageSlider value];
    
    packet = robot_move(conn->data, amount);
    packet_serialize(packet, stream);
    packet_delete(packet);
    
    connection_send_stream(conn, stream, packet_stream_length(stream));
    
    NSMutableString *tempString;
    tempString = [[NSMutableString alloc] initWithString:[debugConsole text]];
    [tempString appendString:@"\nSending Robot Move Backward Packet!"];
    [debugConsole setText:tempString];
    [tempString release];
}

-(IBAction) leftButtonClicked : (id)sender
{
    unsigned char stream[MAX_PACKET_LEN];
    packet_t *packet = NULL;
    float amount = [[amountField text] floatValue] * [percentageSlider value];
    
    packet = robot_rotate(conn->data, amount);
    packet_serialize(packet, stream);
    packet_delete(packet);
    
    connection_send_stream(conn, stream, packet_stream_length(stream));
    
    NSMutableString *tempString;
    tempString = [[NSMutableString alloc] initWithString:[debugConsole text]];
    [tempString appendString:@"\nSending Robot Rotate left Packet!"];
    [debugConsole setText:tempString];
    [tempString release];
}

-(IBAction) rightButtonClicked : (id)sender
{
    unsigned char stream[MAX_PACKET_LEN];
    packet_t *packet = NULL;
    float amount = -[[amountField text] floatValue] * [percentageSlider value];
    
    packet = robot_rotate(conn->data, amount);
    packet_serialize(packet, stream);
    packet_delete(packet);
    
    connection_send_stream(conn, stream, packet_stream_length(stream));
    
    NSMutableString *tempString;
    tempString = [[NSMutableString alloc] initWithString:[debugConsole text]];
    [tempString appendString:@"\nSending Robot Rotate right Packet!"];
    [debugConsole setText:tempString];
    [tempString release];
}


- (void)dealloc
{
    [addressField release];
    [portField release];
    [pingButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // 	Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIAccelerometer *acceletometer = [UIAccelerometer sharedAccelerometer];
    acceletometer.delegate = nil;
    acceletometer.updateInterval = 5.0f/60.0f;
}

-(void) accelerometer:(UIAccelerometer *) accelerometer didAccelerate:(UIAcceleration *)acceleration {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Shake title" message:@"Shake it to wake it!" delegate:nil cancelButtonTitle:@"Cancel B" otherButtonTitles: nil];
    [alert show];
    [alert release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end
